package cn.iocoder.yudao.module.member.service.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.iocoder.yudao.framework.common.enums.TerminalEnum;
import cn.iocoder.yudao.framework.common.enums.UserGasStatusEnum;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.CheckUtils;
import cn.iocoder.yudao.framework.common.util.CollectionUtil;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.infra.api.code.AutoCodeUtilsApi;
import cn.iocoder.yudao.module.member.controller.admin.images.vo.ImagesCreateReqVO;
import cn.iocoder.yudao.module.member.controller.admin.images.vo.ImagesExportReqVO;
import cn.iocoder.yudao.module.member.controller.admin.user.vo.*;
import cn.iocoder.yudao.module.member.controller.admin.usergastemplaterelation.vo.UserGasTemplateRelationSaveReqVO;
import cn.iocoder.yudao.module.member.controller.admin.userrelation.vo.UserRelationCreateReqVO;
import cn.iocoder.yudao.module.member.controller.app.user.vo.*;
import cn.iocoder.yudao.module.member.convert.images.ImagesConvert;
import cn.iocoder.yudao.module.member.convert.user.CrmMemberUserConvert;
import cn.iocoder.yudao.module.member.convert.user.MemberUserConvert;
import cn.iocoder.yudao.module.member.dal.dataobject.images.ImagesDO;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserGasAddressDO;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.dal.dataobject.userrelation.UserRelationDO;
import cn.iocoder.yudao.module.member.dal.mysql.images.ImagesMapper;
import cn.iocoder.yudao.module.member.dal.mysql.user.CrmMemberUserMapper;
import cn.iocoder.yudao.module.member.dal.mysql.user.MemberUserMapper;
import cn.iocoder.yudao.module.member.dal.mysql.userrelation.UserRelationMapper;
import cn.iocoder.yudao.module.member.service.images.ImagesService;
import cn.iocoder.yudao.module.member.service.usergastemplaterelation.UserGasTemplateRelationService;
import cn.iocoder.yudao.module.member.service.userrelation.UserRelationService;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletDO;
import cn.iocoder.yudao.module.pay.service.wallet.PayWalletService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.trade.api.delivery.DeliveryPickUpStoreApi;
import cn.iocoder.yudao.module.trade.api.delivery.dto.DeliveryPickUpStoreDOVo;
import cn.iocoder.yudao.module.trade.api.depositproductrelation.DepositProductRelationApi;
import cn.iocoder.yudao.module.trade.api.depositproductrelation.dto.DepositProductRelationDTO;
import cn.iocoder.yudao.module.trade.api.order.DepositOrderApi;
import cn.iocoder.yudao.module.trade.api.order.TradeOrderApi;
import cn.iocoder.yudao.module.trade.api.order.dto.DepositOrderDTO;
import cn.iocoder.yudao.module.trade.api.order.dto.TradeOrderPageDTO;
import cn.iocoder.yudao.module.trade.api.order.dto.TradeOrderPageItemRespDTO;
import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.USER_CRM_MEMBER_NOT_EXISTS;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.USER_CRM_MEMBER_NOT_STATUS;

/**
 * 燃气户 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class CrmMemberUserServiceImpl implements CrmMemberUserService {

    private static final Log logger = LogFactory.getLog(CrmMemberUserServiceImpl.class);

    @Resource
    private CrmMemberUserMapper crmMemberUserMapper;
    @Resource
    private UserRelationService userRelationService;
    @Resource
    private MemberUserService memberUserService;
    @Resource
    private ImagesService imagesService;
    @Resource
    private ImagesMapper imagesMapper;

    @Resource
    private DeliveryPickUpStoreApi deliveryService;

    @Resource
    private PayWalletService payWalletService;

    @Resource
    private UserRelationMapper userRelationMapper;

    @Resource
    private MemberUserMapper memberUserMapper;

    @Resource
    private AutoCodeUtilsApi autoCodeUtils;

    @Resource
    private DepositProductRelationApi depositProductRelationApi;

    @Resource
    private TradeOrderApi tradeOrderApi;

    @Resource
    private DepositOrderApi depositOrderApi;

    @Resource
    private UserGasTemplateRelationService gasTemplateRelationService;

    @Resource
    private AdminUserApi adminUserApi;

    @Override
    public List<String> getDates(String beginTime,String endTime){
        MemberUserPageReqVO memberUserPageReqVO = new MemberUserPageReqVO();
        memberUserPageReqVO.setBeginTime(beginTime);
        memberUserPageReqVO.setEndTime(endTime);
        return crmMemberUserMapper.selectDateByMonth(memberUserPageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createMemberUser(CrmMemberUserCreateReqVO createReqVO) {
        // 插入
        MemberUserGasAddressDO memberUser = CrmMemberUserConvert.INSTANCE.convert(createReqVO);
        memberUser.setTerminal(createReqVO.getTerminal());
        memberUser.setCode(createReqVO.getCode());

        if (TerminalEnum.WECHAT_MINI_PROGRAM.getTerminal().equals(createReqVO.getTerminal())  || TerminalEnum.WECHAT_WAP.getTerminal().equals(createReqVO.getTerminal())){
            // 来源为小程序或微信则状态设置为  待完善
            memberUser.setStatus(UserGasStatusEnum.BEIMPROVED.getValue());
        } else {
            memberUser.setStatus(UserGasStatusEnum.BEEFFECTIVE.getValue());
        }
        //创建燃气户
        crmMemberUserMapper.insert(memberUser);
        // 获取钱包信息
        payWalletService.getOrCreateWallet(memberUser.getId(), UserTypeEnum.CRM.getValue());

        // 添加关系数据
        UserRelationCreateReqVO userRelationCreateReqVO = composeUserRelationCreateReqVO(memberUser.getId(),createReqVO.getMemberUserId(),createReqVO);
        userRelationService.createUserRelation(userRelationCreateReqVO);

        List<ImageUserVO> list = createReqVO.getImageUserVOS();
        if(!CollectionUtil.isEmpty(list)){
            for(ImageUserVO vo : list){
                ImagesCreateReqVO imagesCreateReqVO = ImagesConvert.INSTANCE.convert(vo);
                imagesCreateReqVO.setStatus(0);
                imagesCreateReqVO.setUserId(memberUser.getId());
                imagesCreateReqVO.setUseType("0");
                imagesService.createImages(imagesCreateReqVO);
            }
        }

        //   创建一条与安检模板记录
        gasTemplateRelationService.createUserGasTemplateRelation(new UserGasTemplateRelationSaveReqVO().setStatus(0).setCrmMemberUserId(memberUser.getId()));
        // 返回
        return memberUser.getId();
    }

    /**
     *  APP新增燃气户
     * @param createReqVO
     * @param terminal
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createMemberUser(AppCrmMemberUserCreateReqVO createReqVO, Integer terminal) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        // 插入
        MemberUserGasAddressDO memberUser = BeanUtils.toBean(createReqVO, MemberUserGasAddressDO.class);
        memberUser.setCode(createReqVO.getCode());
        // 设置来源
        memberUser.setTerminal(terminal);

        // 设置APP创建人（配送员）
        memberUser.setCreator(loginUser.getId().toString());
        crmMemberUserMapper.insert(memberUser);
        // 获取钱包信息
        payWalletService.getOrCreateWallet(memberUser.getId(), UserTypeEnum.CRM.getValue());

        UserRelationCreateReqVO userRelationCreateReqVO = composeUserRelationCreateReqVO(memberUser.getId(),createReqVO.getMemberUserId(), BeanUtils.toBean(createReqVO, CrmMemberUserCreateReqVO.class));
        userRelationService.createUserRelation(userRelationCreateReqVO);

        List<AppImageUserVO> list = createReqVO.getImageUserVOS();
        if(!CollectionUtil.isEmpty(list)){
            for(AppImageUserVO vo : list){
                ImagesCreateReqVO imagesCreateReqVO = BeanUtils.toBean(vo, ImagesCreateReqVO.class);
                imagesCreateReqVO.setStatus(0);
                imagesCreateReqVO.setUserId(memberUser.getId());
                imagesCreateReqVO.setUseType("0");
                imagesService.createImages(imagesCreateReqVO);
            }
        }
        //   创建一条与安检模板记录
        gasTemplateRelationService.createUserGasTemplateRelation(new UserGasTemplateRelationSaveReqVO().setStatus(0).setCrmMemberUserId(memberUser.getId()));
        // 返回
        return memberUser.getId();
    }

    /**
     *  新增燃气户，通过手机号查询memberuser表，有则取数据存到userRelation关系表中
     *   无则新增一条memberuser 初始化数据，再存入关系表
     * @param crmMemberUserId
     * @param memberUserId
     * @param createReqVO
     * @return
     */
    private UserRelationCreateReqVO composeUserRelationCreateReqVO(Long crmMemberUserId,Long memberUserId,CrmMemberUserCreateReqVO createReqVO){
        UserRelationCreateReqVO userRelationCreateReqVO = new UserRelationCreateReqVO();
        userRelationCreateReqVO.setCrmMemberUserId(crmMemberUserId);
        MemberUserDO memberUserDO = memberUserService.getUserByMobile(createReqVO.getMobile());
        userRelationCreateReqVO.setStatus(0);
        userRelationCreateReqVO.setRelation(0);
        if(CheckUtils.isEmpty(memberUserDO)){
            MemberUserDO userDO = new MemberUserDO();
            userDO.setMobile(createReqVO.getMobile());
            // TODO 初始化密码
            userDO.setPassword("888888");
            userDO.setName(createReqVO.getName());
            userDO.setIdNumber(createReqVO.getIdNumber());
            userDO.setNickname(createReqVO.getName());
            MemberUserDO aDo = memberUserService.createMemberUserIfAbsent(MemberUserConvert.INSTANCE.convert03(userDO));
            userRelationCreateReqVO.setMemberUserId(aDo.getId());
        } else {
            userRelationCreateReqVO.setMemberUserId(memberUserDO.getId());
        }
        return userRelationCreateReqVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMemberUser(CrmMemberUserUpdateReqVO updateReqVO) {
        // 校验存在
        validateMemberUserExists(updateReqVO.getId());
        // 更新
        MemberUserGasAddressDO updateObj = CrmMemberUserConvert.INSTANCE.convert(updateReqVO);

        if(CollectionUtil.isEmpty(updateReqVO.getImageUserVOS())){
            return ;
        }

        crmMemberUserMapper.updateById(updateObj);
        List<ImagesDO> imagesDOList = ImagesConvert.INSTANCE.convertList5(updateReqVO.getImageUserVOS());
        if(!CollectionUtil.isEmpty(imagesDOList)){

            List<ImagesDO> doList = imagesService.getImagesListByThirId(updateReqVO.getId(), 0);
                List<Long> list2 = doList.stream().map(ImagesDO::getId).collect(Collectors.toList());
                List<Long> list1 = imagesDOList.stream().map(ImagesDO::getId).collect(Collectors.toList());
                // 通过id比较数据库的图片是否需要删除
                List<Long> diff1 = list2.stream().filter(item -> !list1.contains(item)).collect(Collectors.toList());
                if (!CollectionUtil.isEmpty(diff1)){
                    // 删除图片
                    imagesService.updateImagesIds(diff1);
                }

            for(ImagesDO imagesDO : imagesDOList){
                imagesDO.setUseType("0");
                imagesDO.setThirdId(updateReqVO.getId());
            }
        }
        List<ImagesDO> collect = imagesDOList.stream().filter(item -> StringUtils.isNotEmpty(item.getImageLink())).collect(Collectors.toList());
        imagesService.createUpdateImages(collect);
    }

    /**
     *  用于APP端
     * @param updateReqVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMemberUser(AppCrmMemberUserUpdateReqVO updateReqVO) {
        // 校验存在
        validateMemberUserExists(updateReqVO.getId());
        // 更新
        MemberUserGasAddressDO updateObj = BeanUtils.toBean(updateReqVO, MemberUserGasAddressDO.class);

        if(CollectionUtil.isEmpty(updateReqVO.getImageUserVOS())){
            return ;
        }

        crmMemberUserMapper.updateById(updateObj);

        List<ImagesDO> imagesDOList = BeanUtils.toBean(updateReqVO.getImageUserVOS(), ImagesDO.class);
        if(!CollectionUtil.isEmpty(imagesDOList)){

            List<ImagesDO> doList = imagesService.getImagesListByThirId(updateReqVO.getId(), 0);
            List<Long> list2 = doList.stream().map(ImagesDO::getId).collect(Collectors.toList());
            List<Long> list1 = imagesDOList.stream().map(ImagesDO::getId).collect(Collectors.toList());
            // 通过id比较数据库的图片是否需要删除
            List<Long> diff1 = list2.stream().filter(item -> !list1.contains(item)).collect(Collectors.toList());
            if (!CollectionUtil.isEmpty(diff1)){
                // 删除图片
                imagesService.updateImagesIds(diff1);
            }

            for(ImagesDO imagesDO : imagesDOList){
                imagesDO.setUseType("0");
                imagesDO.setThirdId(updateReqVO.getId());
            }
        }
        List<ImagesDO> collect = imagesDOList.stream().filter(item -> StringUtils.isNotEmpty(item.getImageLink())).collect(Collectors.toList());
        imagesService.createUpdateImages(collect);
    }

    @Override
    public void deleteMemberUser(Long id) {
        // 校验存在
        validateMemberUserExists(id);
        MemberUserGasAddressDO memberUserGasAddressDO = new MemberUserGasAddressDO();
        memberUserGasAddressDO.setId(id);
        memberUserGasAddressDO.setStatus(3);
        // 删除
        crmMemberUserMapper.updateById(memberUserGasAddressDO);
    }

    private void validateMemberUserExists(Long id) {
        if (crmMemberUserMapper.selectById(id) == null) {
            throw exception(USER_CRM_MEMBER_NOT_EXISTS);
        }
    }
    @Override
    public CommonResult<List<MemberUserRespVO>> updateMemberPhone(@RequestBody CrmMemberUserUpdatePhoneReqVO crmMemberUserUpdatePhoneReqVO){
        MemberUserGasAddressDO MemberUserGasAddressDO = getMemberUser(crmMemberUserUpdatePhoneReqVO.getId());
        String inPhone = crmMemberUserUpdatePhoneReqVO.getPhone();
        if(Objects.equals(inPhone, MemberUserGasAddressDO.getMobile())){
            return success(new ArrayList<>());
        }
        CrmMemberUserUpdateReqVO crmMemberUserUpdateReqVO = new CrmMemberUserUpdateReqVO();
        crmMemberUserUpdateReqVO.setId(crmMemberUserUpdatePhoneReqVO.getId());
        crmMemberUserUpdateReqVO.setPhone(inPhone);
        updateMemberUser(crmMemberUserUpdateReqVO);
        Boolean isSuccess = createRelation(inPhone,crmMemberUserUpdatePhoneReqVO.getName() ,crmMemberUserUpdatePhoneReqVO.getId());
        List<UserRelationDO>  userRelationDOS =  userRelationService.getUserRelations(crmMemberUserUpdatePhoneReqVO.getId());
        if(CollectionUtil.isEmpty(userRelationDOS)){
            return success(new ArrayList<>());
        }
        List<Long> crmIdList = userRelationDOS.stream().map(UserRelationDO::getMemberUserId).collect(Collectors.toList());
        List<MemberUserDO>  list = memberUserService.getUserList(crmIdList);
        List<MemberUserRespVO> resultList = BeanUtils.toBean(list,MemberUserRespVO.class);
        resultList.forEach((e) ->{
            if(Objects.equals(e.getMobile(),inPhone)){
                e.setIsDefault(0);
            }else{
                e.setIsDefault(1);
            }
        });
        resultList.sort(Comparator.comparingInt(MemberUserRespVO::getIsDefault));
        if(!isSuccess){
            return error(GlobalErrorCodeConstants.IS_EXITS);
        }
        return success(resultList);

    }

    private Boolean createRelation(String inPhone,String name,Long crmId){
        MemberUserDO memberUserDO = memberUserService.getUserByMobile(inPhone);
        Boolean isSuccess = Boolean.TRUE;
        if(CheckUtils.isEmpty(memberUserDO)){
            MemberUserRespVO memberUserRespVO = new MemberUserRespVO();
            memberUserRespVO.setNickname(name);
            memberUserRespVO.setMobile(inPhone);
            memberUserDO = memberUserService.createMemberUser(memberUserRespVO);
        }else{
            isSuccess = Boolean.FALSE;
        }
        List<UserRelationDO>  userRelationDOS = userRelationService.getUserRelationList(memberUserDO.getId(),crmId);
        if(CollectionUtil.isEmpty(userRelationDOS)){
            UserRelationCreateReqVO userRelationCreateReqVO = new UserRelationCreateReqVO();
            userRelationCreateReqVO.setCrmMemberUserId(crmId);
            userRelationCreateReqVO.setMemberUserId(memberUserDO.getId());
            userRelationCreateReqVO.setRelation(1);
            userRelationCreateReqVO.setStatus(0);
            userRelationService.createUserRelation(userRelationCreateReqVO);
        }
        return isSuccess;
    }


    @Override
    public MemberUserGasAddressDO getMemberUser(Long id) {
        MemberUserGasAddressDO memberUserGasAddressDO = crmMemberUserMapper.selectById(id);
        if (null != memberUserGasAddressDO){
            ImagesExportReqVO reqVO = new ImagesExportReqVO();
            reqVO.setStatus(0);
            reqVO.setThirdId(id);
//            reqVO.setUseType("0");
            List<ImagesDO> imagesDOS = imagesMapper.selectList(reqVO);
            memberUserGasAddressDO.setImgList(CollectionUtil.isEmpty(imagesDOS) ? null : imagesDOS);
            if (CheckUtils.isEmpty(memberUserGasAddressDO.getNearbyStoreId())){
                // 查询门店名称
                DeliveryPickUpStoreDOVo pick = deliveryService.selectById(memberUserGasAddressDO.getNearbyStoreId());
                memberUserGasAddressDO.setStoreName(pick.getName());
            }

            // 查询和户主关系表的户主id
            LambdaQueryWrapperX<UserRelationDO> wrapper = new LambdaQueryWrapperX<>();
            wrapper.eq(UserRelationDO ::getCrmMemberUserId, id ).eq(UserRelationDO :: getRelation, 0 );
            UserRelationDO userRelationDO = userRelationMapper.selectOne(wrapper);
            // 查询户主钱包
            PayWalletDO payWalletDO = payWalletService.getWalletByMemberUserId(userRelationDO.getMemberUserId());


            // 查询户主信息
            MemberUserDO memberUserDO = memberUserMapper.selectById(userRelationDO.getMemberUserId());
            if (!CheckUtils.isEmpty(payWalletDO)){
                memberUserGasAddressDO.setPoint(payWalletDO.getPoint());
//            memberUserGasAddressDO.setFreezePrice(payWalletDO.getFreezePrice());
                memberUserGasAddressDO.setTotalRecharge(payWalletDO.getTotalRecharge());
                memberUserGasAddressDO.setCreditAmount(payWalletDO.getCreditAmount());
                memberUserGasAddressDO.setBalance(payWalletDO.getBalance());
                memberUserGasAddressDO.setTotalExpense(payWalletDO.getTotalExpense());
                memberUserGasAddressDO.setUserType(payWalletDO.getUserType());
            }

            memberUserGasAddressDO.setMark(memberUserDO.getMark());
            memberUserGasAddressDO.setAvatar(memberUserDO.getAvatar());
            memberUserGasAddressDO.setIsOff(memberUserDO.getStatus());

            memberUserGasAddressDO.setNickName(memberUserDO.getNickname());
            // 查询押金对应的钢瓶数量
            memberUserGasAddressDO.setDepositBottleCount( depositOrderApi.selectOrderByGasId(id));

            //
            memberUserGasAddressDO.setCreator(adminUserApi.getUser(Long.valueOf(memberUserGasAddressDO.getCreator())).getNickname());
        }
        return memberUserGasAddressDO;
    }
    @Override
    public AppCrmMemberUserRespVO getMemberUserApp(Long id) {
        MemberUserGasAddressDO memberUserGasAddressDO = crmMemberUserMapper.selectById(id);
        if (null != memberUserGasAddressDO){
            ImagesExportReqVO reqVO = new ImagesExportReqVO();
            reqVO.setStatus(0);
            reqVO.setThirdId(id);
//            reqVO.setUseType("0");
            List<ImagesDO> imagesDOS = imagesMapper.selectList(reqVO);
            memberUserGasAddressDO.setImgList(CollectionUtil.isEmpty(imagesDOS) ? null : imagesDOS);
            if (CheckUtils.isEmpty(memberUserGasAddressDO.getNearbyStoreId())){
                // 查询门店名称
                DeliveryPickUpStoreDOVo pick = deliveryService.selectById(memberUserGasAddressDO.getNearbyStoreId());
                memberUserGasAddressDO.setStoreName(pick.getName());
            }

            // 查询和户主关系表的户主id
            LambdaQueryWrapperX<UserRelationDO> wrapper = new LambdaQueryWrapperX<>();
            wrapper.eq(UserRelationDO ::getCrmMemberUserId, id ).eq(UserRelationDO :: getRelation, 0 );
            UserRelationDO userRelationDO = userRelationMapper.selectOne(wrapper);
            // 查询户主钱包
            PayWalletDO payWalletDO = payWalletService.getWalletByMemberUserId(userRelationDO.getMemberUserId());


            // 查询户主信息
            MemberUserDO memberUserDO = memberUserMapper.selectById(userRelationDO.getMemberUserId());
            if (!CheckUtils.isEmpty(payWalletDO)){
                memberUserGasAddressDO.setPoint(payWalletDO.getPoint());
//            memberUserGasAddressDO.setFreezePrice(payWalletDO.getFreezePrice());
                memberUserGasAddressDO.setTotalRecharge(payWalletDO.getTotalRecharge());
                memberUserGasAddressDO.setCreditAmount(payWalletDO.getCreditAmount());
                memberUserGasAddressDO.setBalance(payWalletDO.getBalance());
                memberUserGasAddressDO.setTotalExpense(payWalletDO.getTotalExpense());
                memberUserGasAddressDO.setUserType(payWalletDO.getUserType());
            }

            memberUserGasAddressDO.setMark(memberUserDO.getMark());
            memberUserGasAddressDO.setAvatar(memberUserDO.getAvatar());
            memberUserGasAddressDO.setIsOff(memberUserDO.getStatus());

            memberUserGasAddressDO.setNickName(memberUserDO.getNickname());
            // 查询押金对应的钢瓶数量
            memberUserGasAddressDO.setDepositBottleCount( depositOrderApi.selectOrderByGasId(id));

            //
            memberUserGasAddressDO.setCreator(adminUserApi.getUser(Long.valueOf(memberUserGasAddressDO.getCreator())).getNickname());
            AppCrmMemberUserRespVO appCrmMemberUserRespVO = BeanUtils.toBean(memberUserGasAddressDO, AppCrmMemberUserRespVO.class);

            // 查询押金单
            appCrmMemberUserRespVO.setDepositProductRelationDTOS(CollectionUtil.isEmpty(depositProductRelationApi.selectDepositProductByDepositId(memberUserGasAddressDO.getId())) ? null : depositProductRelationApi.selectDepositProductByDepositId(memberUserGasAddressDO.getId()));
            return appCrmMemberUserRespVO;
        }
        return null;
    }

    /**
     *  根据多个id查询多个燃气户信息
     * @param ids 编号
     * @return
     */
    @Override
    public List<MemberUserGasAddressDO> getMemberUserList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return crmMemberUserMapper.selectBatchIds(ids);
    }

    /**
     *  分页查询燃气户
     * @param pageReqVO 分页查询
     * @return
     */
    @Override
    public PageResult<CrmMemberUserRespVO> getMemberUserPage(CrmMemberUserPageReqVO pageReqVO) {
        PageResult<MemberUserGasAddressDO> page = crmMemberUserMapper.selectPage(pageReqVO);
        PageResult<CrmMemberUserRespVO> result = CrmMemberUserConvert.INSTANCE.convertPage(new PageResult<MemberUserGasAddressDO>(page.getList(), page.getTotal()));
        if (!CollectionUtil.isEmpty(result.getList())){
            result.getList().forEach(x -> {
                UserRelationDO userRelationDO = userRelationService.getUserRelationOne(x.getId());
                if(CheckUtils.isEmpty(userRelationDO)){
                    return;
                }
                x.setMemberUserId(userRelationDO.getMemberUserId());

                List<DepositOrderDTO> depositOrderDTOS = depositOrderApi.selectOrderByGasIdList(x.getId());

                // 计算压瓶数量
                AtomicReference<Integer> sum = new AtomicReference<>(0);
                depositOrderDTOS.forEach(y -> {

                    List<DepositProductRelationDTO> depositProductRelationDOS = depositProductRelationApi.selectDepositByDepositId(y.getId());
                    sum.updateAndGet(v -> v + depositProductRelationDOS.stream().mapToInt(DepositProductRelationDTO::getSkuCount).sum());
                });
                // 押金压瓶数量
                x.setDepositBottleCount(sum.get());

                PayWalletDO orCreateWallet = payWalletService.getWalletByMemberUserId(userRelationDO.getMemberUserId());
                // 账户余额
                x.setBalance(orCreateWallet.getBalance());

                // 查询燃气户订单数量
                x.setOrderCount(tradeOrderApi.getOrderCountByUserGasId(x.getId()));
            });
        }
//        }
        return result;
    }

    /**
     *  APP端查询燃气户
     * @param pageReqVO 分页查询
     * @return
     */
    @Override
    public PageResult<AppCrmMemberUserRespVO> getAppMemberUserPage(AppCrmMemberUserPageReqVO pageReqVO) {
        PageResult<MemberUserGasAddressDO> page = crmMemberUserMapper.selectPage(BeanUtils.toBean(pageReqVO, CrmMemberUserPageReqVO.class));
        PageResult<CrmMemberUserRespVO> result = CrmMemberUserConvert.INSTANCE.convertPage(new PageResult<MemberUserGasAddressDO>(page.getList(), page.getTotal()));
        if (!CollectionUtil.isEmpty(result.getList())){
            result.getList().forEach(x -> {
                UserRelationDO userRelationDO = userRelationService.getUserRelationOne(x.getId());
                if(CheckUtils.isEmpty(userRelationDO)){
                    return;
                }
                x.setMemberUserId(userRelationDO.getMemberUserId());

                List<DepositOrderDTO> depositOrderDTOS = depositOrderApi.selectOrderByGasIdList(x.getId());

                // 计算压瓶数量
                AtomicReference<Integer> sum = new AtomicReference<>(0);
                depositOrderDTOS.forEach(y -> {

                    List<DepositProductRelationDTO> depositProductRelationDOS = depositProductRelationApi.selectDepositByDepositId(y.getId());
                    sum.updateAndGet(v -> v + depositProductRelationDOS.stream().mapToInt(DepositProductRelationDTO::getSkuCount).sum());
                });
                // 押金压瓶数量
                x.setDepositBottleCount(sum.get());

//                PayWalletDO orCreateWallet = payWalletService.getWalletByMemberUserId(userRelationDO.getMemberUserId());
//                // 账户余额
//                x.setBalance(orCreateWallet.getBalance());

                // 查询燃气户订单数量
//                x.setOrderCount(tradeOrderApi.getOrderCountByUserGasId(x.getId()));
            });
        } else {
            return new PageResult<>();
        }
        return BeanUtils.toBean(result, AppCrmMemberUserRespVO.class);
    }

    @Override
    public List<MemberUserGasAddressDO> getMemberUserList(CrmMemberUserExportReqVO exportReqVO) {
        return crmMemberUserMapper.selectList(exportReqVO);
    }

    /**
     *  新规则code生成
     * @return
     */
    @Override
    public String getCodeByDate(String key) {
        if ("delivery_person_info".equals(key)) {
            return autoCodeUtils.DeliveryPersonCode(key);
        }
       // 新生成规则：年 + 月 + 日 + 时分秒 +当日自增序列
        // 调用code自动生成工具类
        return autoCodeUtils.autoCode(key, autoCodeUtils.timeCode());
    }

    /**
     *  燃气户订单分页
     * @param dto
     * @return
     */
    @Override
    public PageResult<TradeOrderPageItemRespDTO> getOrderByCrmId(TradeOrderPageDTO dto) {
        // 校验是否存在燃气户
        validateMemberExists(dto.getId());
        PageResult<TradeOrderPageItemRespDTO> idList = tradeOrderApi.selectTradeOrderByGasIdList(dto);

        return idList;
    }

    /**
     *  审核燃气户
     * @param updateReqVO
     */
    @Override
    public void examineMemberUser(CrmMemberUserUpdateReqVO updateReqVO) {
        validateMemberExists(updateReqVO.getId());
        // 只能审核待生效
        crmMemberUserMapper.updateById(BeanUtils.toBean(updateReqVO, MemberUserGasAddressDO.class));
    }

    @Override
    public PageResult<AppAdminUserRespDTO> getAppSalesmanNameList(AppAdminUserRespDTO dto) {
        PageResult<AdminUserRespDTO> pageResult = adminUserApi.pageUserRespDTO(BeanUtils.toBean(dto, AdminUserRespDTO.class));
        return BeanUtils.toBean(pageResult, AppAdminUserRespDTO.class);
    }

    private void validateMemberExists(Long id) {
        MemberUserGasAddressDO addressDO = crmMemberUserMapper.selectById(id);
        if (addressDO == null) {
            throw exception(USER_CRM_MEMBER_NOT_EXISTS);
        }
    }
}
